package com.emily.test.utils;

import com.emily.test.constant.ReturnValueConstants;
import javafx.beans.binding.ObjectExpression;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * 针对文件的操作工具类
 * @author  田庆新
 */
public class FileOperateUtil {
	/**
	 * 拷贝文件
	 * 
	 * @param src
	 *            文件源目录
	 * @param dest
	 *            文件目的目录
	 * @throws FileNotFoundException
	 * @throws IOException
	 */
	public void copyFile(String src, String dest) throws FileNotFoundException, IOException {
		FileInputStream in = null;
		FileOutputStream out = null;
		try {
			in = new FileInputStream(src);
			File file = new File(dest);
			if (!file.exists())
				file.createNewFile();
			out = new FileOutputStream(file);
			int c;
			byte buffer[] = new byte[1024];
			while ((c = in.read(buffer)) != -1) {
				for (int i = 0; i < c; i++)
					out.write(buffer[i]);
			}
		} finally {
			try {
				if (in != null) {
					in.close();
					in = null;
				}
				if (out != null) {
					out.close();
					out = null;
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * 创建目录
	 * 
	 * @param path
	 */
	public void createDir(String path) {
		File dir = new File(path);
		if (!dir.exists())
			dir.mkdirs();
	}

	/**
	 * 创建文件
	 * 
	 * @param path
	 * @param fileName
	 * @throws IOException
	 */
	public void createFile(String path, String fileName) throws IOException {
		File file = new File(path + "/" + fileName);
		if (!file.exists()) {
			file.createNewFile();
		}
	}

	/**
	 * 创建文件
	 * 
	 * @param filepath
	 * @throws IOException
	 */
	public void createFile(String filepath) throws IOException {
		File file = new File(filepath);
		if (!file.exists()) {
			file.createNewFile();
		}
	}

	/**
	 * 删除文件夹
	 * 
	 * @param path
	 */
	public void delDir(String path) {
		File dir = new File(path);
		if (dir.exists()) {
			File[] tmp = dir.listFiles();
			for (int i = 0; i < tmp.length; i++) {
				if (tmp[i].isDirectory()) {
					delDir(path + "/" + tmp[i].getName());
				} else {
					tmp[i].delete();
				}
			}
			dir.delete();
		}
	}

	/**
	 * 删除文件
	 * 
	 * @param path
	 *            目录
	 * @param filename
	 *            文件名
	 */
	public void delFile(String path, String filename) {
		File file = new File(path + "/" + filename);
		if (file.exists() && file.isFile())
			file.delete();
	}

	/**
	 * 删除文件
	 * 
	 * @param path
	 *            文件路径
	 */
	public void delFile(String path) {
		File file = new File(path);
		if (file.exists() && file.isFile())
			file.delete();
	}

	/**
	 * 读文件
	 * 
	 * @param path
	 * @throws FileNotFoundException
	 * @throws IOException
	 * @return
	 */
	public String readFile(String path) throws FileNotFoundException, IOException {
		String fileStr = "";
		BufferedReader br = null;
		try {
			File file = new File(path);
			br = new BufferedReader(new FileReader(file));
			String temp = null;
			StringBuffer sb = new StringBuffer();
			temp = br.readLine();
			while (temp != null) {
				sb.append(temp);
				temp = br.readLine();
			}
			fileStr = sb.toString();
		} finally {
			try {
				if (br != null) {
					br.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return fileStr;
	}

	/**
	 * 向文件里写数据
	 * 
	 * @param path
	 * @throws FileNotFoundException
	 * @throws IOException
	 */
	public void writeFile(String path, String fileName, String data) throws FileNotFoundException, IOException {
		FileOutputStream out = null;
		try {
			File dir = new File(path);
			if (!dir.exists())
				dir.mkdirs();
			File file = new File(path + fileName);
			if (!file.exists()) {
				file.createNewFile();
			}
			out = new FileOutputStream(file);
			out.write(data.getBytes());
		} finally {
			try {
				if (out != null) {
					out.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * 向文件里写数据
	 * 
	 * @param path
	 * @throws FileNotFoundException
	 * @throws IOException
	 */
	public void writeFile(String path, String fileName, byte[] data) throws FileNotFoundException, IOException {
		FileOutputStream out = null;
		try {
			File dir = new File(path);
			if (!dir.exists())
				dir.mkdirs();
			File file = new File(path + fileName);
			if (!file.exists()) {
				file.createNewFile();
			}
			out = new FileOutputStream(file);
			out.write(data);
		} finally {
			try {
				if (out != null) {
					out.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
	/**
	 * 获得指定文件的byte数组
	 */
	public byte[] getBytesbyfile(String filePath) {
		byte[] buffer = null;
		try {
			File file = new File(filePath);
			FileInputStream fis = new FileInputStream(file);
			ByteArrayOutputStream bos = new ByteArrayOutputStream(1000);
			byte[] b = new byte[1000];
			int n;
			while ((n = fis.read(b)) != -1) {
				bos.write(b, 0, n);
			}
			fis.close();
			bos.close();
			buffer = bos.toByteArray();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return buffer;
	}

	/**
	 * 根据byte数组，生成文件
	 */
	public String getFile(byte[] bfile, String filePath, String fileName) {
		FileOutputStream out = null;
		String filePathW = "";
		try {
			// System.out.println(DateFormat.getDateTime()+"：  getFile(filePath)="+filePath);
			// System.out.println(DateFormat.getDateTime()+"：  getFile(fileName)="+fileName);
			// System.out.println(DateFormat.getDateTime()+"：  getFile(filePath +File.pathSeparator + fileName)="+filePath +File.pathSeparator + fileName);
			File dir = new File(filePath);
			if (!dir.exists())
				dir.mkdirs();
			filePathW = filePath + "/" + fileName;
			File file = new File(filePath + "/" + fileName);
			if (!file.exists()) {
				file.createNewFile();
			}
			out = new FileOutputStream(file);
			out.write(bfile);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (out != null) {
					out.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return filePathW;
	}

	/**
	 * 读取本地图片获取输入流
	 * @param path 本地路径
	 * @return
	 * @throws IOException
	 */
	public static FileInputStream readImage(String path) throws IOException {
		return new FileInputStream(new File(path));
	}

	/**
	 * 读取表中图片获取输出流
	 * @param in
	 * @param targetPath
	 */
	public static void readBin2Image(InputStream in, String targetPath) {
		File file = new File(targetPath);
		String path = targetPath.substring(0, targetPath.lastIndexOf("/"));
		if (!file.exists()) {
			new File(path).mkdir();
		}
		FileOutputStream fos = null;
		try {
			fos = new FileOutputStream(file);
			int len = 0;
			byte[] buf = new byte[1024];
			while ((len = in.read(buf)) != -1) {
				fos.write(buf, 0, len);
			}
			fos.flush();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (null != fos) {
				try {
					fos.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}

	public static String fileUpload(Map<String, Object> files, HttpServletRequest request) throws IOException {
		String BOUNDARY = "---------7d4a6d158c9"; // 定义数据分隔线
		//获取服务端存放图片的url
		String serverUrl=ConstentUtil.getRequestPath(request)+"/img";
		URL url = new URL(serverUrl);
		HttpURLConnection conn = (HttpURLConnection) url.openConnection();
		// 发送POST请求必须设置如下两行
		conn.setDoOutput(true);
		conn.setDoInput(true);
		conn.setUseCaches(false);
		conn.setRequestMethod("POST");
		conn.setRequestProperty("connection", "Keep-Alive");
		conn.setRequestProperty("user-agent",
				"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");
		conn.setRequestProperty("Charsert", "UTF-8");
		conn.setRequestProperty("Content-Type",
				"multipart/form-data; boundary=" + BOUNDARY);

		OutputStream out = new DataOutputStream(conn.getOutputStream());
		byte[] end_data = ("\r\n--" + BOUNDARY + "--\r\n").getBytes();// 定义最后数据分隔线
		String fileName= (String) files.get("fileName");
//		String fileType=(String) files.get("fileContentType");
		HashMap<String, InputStream> file1= (HashMap<String, InputStream>) files.get("inputStream");
		Iterator iter = file1.entrySet().iterator();
		int i=0;
		while (iter.hasNext()) {
			i++;
			Map.Entry entry = (Map.Entry) iter.next();
			String key = (String) entry.getKey();
			InputStream val = (InputStream) entry.getValue();
			String fname = key;
			File file = new File(fname);
			StringBuilder sb = new StringBuilder();
			sb.append("--");
			sb.append(BOUNDARY);
			sb.append("\r\n");
			sb.append("Content-Disposition: form-data;name=\"file" + i
					+ "\";filename=\"" + key + "\"\r\n");
			sb.append("Content-Type:application/octet-stream\r\n\r\n");

			byte[] data = sb.toString().getBytes();
			out.write(data);
			DataInputStream in = new DataInputStream(val);
			int bytes = 0;
			byte[] bufferOut = new byte[1024];
			while ((bytes = in.read(bufferOut)) != -1) {
				out.write(bufferOut, 0, bytes);
			}
			out.write("\r\n".getBytes()); // 多个文件时，二个文件之间加入这个
			in.close();
		}
		out.write(end_data);
		out.flush();
		out.close();

		// 定义BufferedReader输入流来读取URL的响应
		BufferedReader reader = new BufferedReader(new InputStreamReader(
				conn.getInputStream(), "UTF-8"));
		String line = null;
		while ((line = reader.readLine()) != null) {
			System.out.println(line);
		}
		return serverUrl+"/"+fileName;
	}
}
